package com.customization.huangwm.workflowNodeAction.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.customization.huangwm.dao.SW003.LoggingDao;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2023-03-07
 * @Version 1.0 
 * @Description TODO 增加對於物料庫存數量的校驗，調用YY接口，在出庫管理部門審批時OA方的庫存跟YY庫存不一致時不允許提交
 **/
public class CheckStockNum implements Action {

    private LogTool log = new LogTool("/log/SW003/huangwm/WfAction/CheckStockNum", false);
    private DBTools dbTools = new DBTools();
    private DateTools dateTools = new DateTools();

    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        String nodeType = requestInfo.getRequestManager().getNodetype();
        String src = requestInfo.getRequestManager().getSrc();
        log.writeLog("前置檢查物料庫存數量 requestid="+requestid);

        LoggingDao loggingDao = new LoggingDao();

        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        try{
            String tableName = requestInfo.getRequestManager().getBillTableName();
            String billid = requestInfo.getRequestManager().getBillid() + "";
            String sql = "select  sum(REVIEWQUANTITY) as reviewQuantity,assetCode from "+tableName+"_dt2 where mainid="+billid +
                    "group by assetCode ";
            log.writeLog(sql);
            rs.execute(sql);
            List<String> invcodes = new ArrayList<>();
            List<Map<String,Object>> thisdata = new ArrayList<>();
            while (rs.next()){
                Map<String,Object> data = new HashMap<>();
                String assetid= rs.getString("assetCode");
                String assetCode = dbTools.getAssetCode(rs2, assetid);
                Double reviewQuantity = rs.getDouble("reviewQuantity");
                data.put("assetCode",assetCode);
                data.put("reviewQuantity",reviewQuantity);
                thisdata.add(data);
                invcodes.add(assetCode);
            }
            if(invcodes.size()<1 || thisdata.size()<1){
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("審核時檢查YY庫存數量-獲取表單itemcode爲空");
                return FAILURE_AND_CONTINUE;
            }

            //先對接用友 再提交更新，對接失敗則rollback
            String eop_reqUrl = new BaseBean().getPropValue("SW003", "eop_reqUrl");
            if (eop_reqUrl.isEmpty()) {
                eop_reqUrl = "https://testeop.macaowater.com";
            }
            String eop_reqToken = new BaseBean().getPropValue("SW003", "eop_reqToken");
            if (eop_reqToken.isEmpty()) {
                eop_reqToken = "EapUfida20200630D1207F4TEST";
            }
            HttpRequest http = new HttpRequest();
            JSONObject params = new JSONObject();
            params.put("reqNb", http.getTimestamp());
            params.put("reqLang", "zh");
            params.put("reqToken", eop_reqToken);
            Map<String, Object> reqData = new HashMap<>();
            //添加billHead至reqData
            reqData.put("invcodes", invcodes);
            params.put("reqData",reqData);
            log.writeLog("---傳入用友參數如下---");
            log.writeLog(JSON.toJSONString(params));
            JSONObject json = http.CallApiPost(eop_reqUrl + "/eop/eapToUfida/getMaterialStockNum", JSONObject.toJSONString(params));
            log.writeLog("---傳入用友結果如下---");
            log.writeLog(JSON.toJSONString(json));
            loggingDao.wrtieLog("0", "/eop/eapToUfida/getMaterialStockNum", JSON.toJSONString(params), JSON.toJSONString(json));
            //对接用友
            if (json == null || !json.getString("state").equals("0")) {
                requestInfo.getRequestManager().setMessageid(requestid);
                requestInfo.getRequestManager().setMessagecontent("審核時檢查YY庫存數量異常;\n" + JSON.toJSONString(json));
                return FAILURE_AND_CONTINUE;
            } else {
                //對比OA數據與用友返回的數據
                JSONArray data = json.getJSONObject("result").getJSONArray("data");
                if(data==null || data.size()<1){
                    requestInfo.getRequestManager().setMessageid(requestid);
                    requestInfo.getRequestManager().setMessagecontent("審核時檢查YY庫存數量失敗;用友返回結果為空");
                    return FAILURE_AND_CONTINUE;
                }

                //循環對比
                for(int i=0;i<data.size();i++){
                    JSONObject map1 = data.getJSONObject(i);
                    String code1 = map1.get("invcode").toString();
                    Double num1 = Double.parseDouble(map1.get("num").toString());
                    for(int j=0;j<thisdata.size();j++ ){
                        Map<String,Object> map2 = thisdata.get(j);
                        String code2 = map2.get("assetCode").toString();
                        Double num2 = Double.parseDouble(map2.get("reviewQuantity").toString());
                        if(code1.equals(code2)){
                            if(num1<num2){
                                requestInfo.getRequestManager().setMessageid(requestid);
                                requestInfo.getRequestManager().setMessagecontent("物料編號:"+code1+"在用友的庫存數:"+num1+" 小於本次EAP申請數:"+num2);
                                return FAILURE_AND_CONTINUE;
                            }
                        }
                    }

                }
            }

        }catch (Exception e){
            e.printStackTrace();
            requestInfo.getRequestManager().setMessageid(requestid);
            requestInfo.getRequestManager().setMessagecontent("審核時檢查YY庫存數量-程序異常 "+e.getMessage());
            return FAILURE_AND_CONTINUE;
        }

        return SUCCESS;
    }
}
